import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';

export async function GET(request: NextRequest) {
  try {
    const db = getDeviceParameterDb();
    const { searchParams } = new URL(request.url);
    const specialty = searchParams.get('specialty');

    let devices = db.getAllDevices();
    if (specialty) {
      devices = devices.filter(device => device.specialty === specialty);
    }

    return NextResponse.json({
      success: true,
      data: devices
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'An unknown error occurred';
    console.error(`Failed to get devices: ${message}`);
    return NextResponse.json({
      success: false,
      error: message
    }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const db = getDeviceParameterDb();
    const deviceData = await request.json();
    
    // 确保必要字段存在
    if (!deviceData.specialty || !deviceData.id || !deviceData.name) {
      return NextResponse.json({
        success: false,
        error: '缺少必要字段: specialty, id, name'
      }, { status: 400 });
    }

    // 使用SQLite插入设备数据
    const deviceParameterDb = db as any;
    const stmt = deviceParameterDb.db.prepare(`
      INSERT INTO devices (
        device_id, name, specialty, classification_name, classification_code,
        naming_table_id, position_table_id, base_params_table_id, tech_spec_table_id,
        sequence_number, remarks, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
    `);
    
    const result = stmt.run(
      deviceData.id,
      deviceData.name,
      deviceData.specialty,
      deviceData.classification_name || '',
      deviceData.classification_code || '',
      deviceData.namingTableId || '',
      deviceData.positionTableId || '',
      deviceData.baseParamsTableId || '',
      deviceData.techSpecTableId || '',
      deviceData.序号 || '',
      deviceData.备注 || ''
    );
    
    return NextResponse.json({
      success: true,
      data: { id: result.lastInsertRowid, ...deviceData }
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'An unknown error occurred';
    console.error(`Failed to add device: ${message}`);
    return NextResponse.json({
      success: false,
      error: message
    }, { status: 500 });
  }
} 